package back

import (
	"fmt"
	"math"
	"net/http"
	"strconv"
	"time"
	"tmall_go/models"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type UserController struct{}

type TransUser struct {
	models.User      // 结构体嵌套-继承
	MyTag       bool // 额外字段
}

func (con UserController) PageList(c *gin.Context) {
	// 验证用户是否过期
	idStr, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	resStrTag := c.Query("res")
	id, _ := strconv.Atoi(idStr)
	userName, _ := c.Cookie("name")
	authority, _ := c.Cookie("authority")

	numStr := c.Param("num")
	curPage, _ := strconv.Atoi(numStr)
	curTiao := 0
	var sumPage int64 = 0
	var sumTiao int64 = 0
	pageSize := 5
	userList := []models.User{}
	allList := []models.User{}
	if authority == "admin" {
		models.DB.Order("update_time desc").Offset((curPage - 1) * pageSize).Limit(pageSize).Find(&userList)
		models.DB.Find(&allList).Count(&sumTiao)
	} else {
		models.DB.Where("id=?", id).Find(&userList)
		models.DB.Where("id=?", id).Find(&allList).Count(&sumTiao)
	}
	sumPage = int64(math.Ceil(float64(sumTiao) / float64(pageSize)))
	curTiao = len(userList)
	agsList := make([]TransUser, curTiao, curTiao) // 创建长度为curTiao，容量为curTiao切片
	for ind, item := range userList {
		agsList[ind].Id = item.Id
		agsList[ind].Name = item.Name
		agsList[ind].Sex = item.Sex
		agsList[ind].Age = item.Age
		agsList[ind].Address = item.Address
		agsList[ind].CreateTime = item.CreateTime
		agsList[ind].UpdateTime = item.UpdateTime
		if item.Id == id {
			agsList[ind].MyTag = true
		} else {
			agsList[ind].MyTag = false
		}
	}
	c.HTML(http.StatusOK, "backstage/index.html", gin.H{
		"barKey":    2,
		"userName":  userName,
		"authority": authority,
		"errTag":    resStrTag,
		"info":      agsList,
		"curPage":   curPage,
		"curTiao":   curTiao,
		"sumPage":   sumPage,
		"sumTiao":   sumTiao,
		"pageSize":  pageSize,
	})
}
func (con UserController) DoUser(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	id := c.Param("id")
	name := c.PostForm("name")
	sex := c.PostForm("sex")
	age := c.PostForm("age")
	address := c.PostForm("address")
	fmt.Println("user-date:", id, name, sex, age, address)

	idNum, _ := strconv.Atoi(id)
	sexNum, _ := strconv.Atoi(sex)
	ageNum, _ := strconv.Atoi(age)
	if idNum == 0 {
		initPwd := "123"
		// bcrypt加密，后面通过它自带的方法进行密码对比
		resPwd, _ := bcrypt.GenerateFromPassword([]byte(initPwd), bcrypt.DefaultCost)
		user := models.User{
			Name:       name,
			Password:   string(resPwd),
			Sex:        sexNum,
			Age:        ageNum,
			Address:    address,
			CreateTime: time.Now().Format("2006-01-02 15:04:05"),
			UpdateTime: time.Now().Format("2006-01-02 15:04:05"),
		}
		models.DB.Create(&user)
		c.Redirect(http.StatusFound, "/back/userMgr/curPage/1?res=1")
	} else if idNum > 0 {
		user := models.User{Id: idNum}
		models.DB.Find(&user)
		user.Name = name
		user.Sex = sexNum
		user.Age = ageNum
		user.Address = address
		user.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
		models.DB.Save(&user)
		c.Redirect(http.StatusFound, "/back/userMgr/curPage/1?res=1")
	} else {
		c.Redirect(http.StatusFound, "/back/userMgr/curPage/1?res=-1")
	}
}
func (con UserController) AddUser(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	c.HTML(http.StatusOK, "backstage/userInfo.html", gin.H{
		"optKey": 1,
		"info":   models.User{},
	})
}
func (con UserController) EditUser(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	id := c.Param("id")
	userObj := models.User{}
	models.DB.Where("id=?", id).Find(&userObj)
	c.HTML(http.StatusOK, "backstage/userInfo.html", gin.H{
		"optKey": 2,
		"info":   userObj,
	})
}
func (con UserController) DeleteUser(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	id := c.Param("id")
	idNum, _ := strconv.Atoi(id)
	user := models.User{Id: idNum}
	models.DB.Delete(&user)
	c.Redirect(http.StatusFound, "/back/userMgr/curPage/1?res=1")
}
func (con UserController) DetailUser(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	id := c.Param("id")
	userObj := models.User{}
	models.DB.Where("id=?", id).Find(&userObj)
	c.HTML(http.StatusOK, "backstage/userInfo.html", gin.H{
		"optKey": 3,
		"info":   userObj,
	})
}
func (con UserController) ResetPwd(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	id := c.Param("id")
	idNum, _ := strconv.Atoi(id)
	user := models.User{Id: idNum}
	models.DB.Find(&user)
	initPwd := "123"
	// bcrypt加密，后面通过它自带的方法进行密码对比
	resPwd, _ := bcrypt.GenerateFromPassword([]byte(initPwd), bcrypt.DefaultCost)
	user.Password = string(resPwd)
	user.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	models.DB.Save(&user)
	c.Redirect(http.StatusFound, "/back/userMgr/curPage/1?res=1")
}
